package com.jiangore.config.redis;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;



/**
 * @Todo 这个配置只适用于key为String的情况，如果key为Long则这个配置要去掉
 * @Author jiangtao
 * @CreateBy 2020-03-05 9:24 PM
 * @UpdateBy jiangtao
 * @Version v1.0
 */

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        RedisSerializer stringSerializer = new StringRedisSerializer();
        //使用fastjson 序列化
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);

        redisTemplate.setKeySerializer(stringSerializer);                   //key序列化
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);          //使用fastjson 序列化

        redisTemplate.setHashKeySerializer(stringSerializer);               //Hash key序列化
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);      //使用fastjson 序列化
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }


}

